/**
 * 用户个人主页
 */
$(function () {
    var user_id = $("#userId").data("id"),
        fundType = $("select[name=fundType]"),
        fundOperation = $("select[name=fundOperation]"),
        fundStatus = $("select[name=fundStatus]");

    /**
     * 读取资金账户
     */
    var initUserFund = function () {
        $.get("fund/getUserFund/" + user_id, function (fund) {
            if (fund !== null) {
                $("#available-amount").text($.number(fund.available, 2));
                $("#frozen-amount").text($.number(fund.frozen, 2));
                $("#receivable-amount").text($.number(fund.receivable, 2));
                $("#payable-amount").text($.number(fund.payable, 2));
                $("#total-deposit").text($.number(fund.totalDeposit, 2));
                $("#total-withdraw").text($.number(fund.totalWithdraw, 2));
            } else {
                alert("读取用户资金账户失败");
            }
        });
    };

    /**
     * 初始化资金记录列表
     */
    var initFundRecordTable = function () {
        // 初始化资金类型下拉列表
        for (var type in sysFundType) {
            fundType.append($("<option></option>").attr("value", type).text(sysFundType[type]));
        }
        // 初始化操作类型下拉列表
        for (var type in sysFundOperation) {
            fundOperation.append($("<option></option>").attr("value", type).text(sysFundOperation[type]));
        }
        // 初始化资金状态下拉列表
        for (var type in sysFundStatus) {
            fundStatus.append($("<option></option>").attr("value", type).text(sysFundStatus[type]));
        }
        // 初始化列表
        var table = $('#fundRecordList').DataTable({
//            "processing": true,
//            "serverSide": true,
            "ajax": {
                "url": "fund/getUserFundRecord",
                "data": function (d) {
                    d.userId = user_id;
                    d.fundType = fundType.val();
                    d.fundOperation = fundOperation.val();
                    d.fundStatus = fundStatus.val();
                },
                "type": "POST"
            },
            "columns": [
                {"data": "orderId"},
                {"data": "orderId"}, //transId
                {"data": "amount"},
                {"data": "type"},
                {"data": "operation"},
                {"data": "status"},
                {"data": "recordTime"},
                {"data": "description"}
            ],
            "aoColumnDefs": [{
                    "targets": 1, //流水号
                    "visible": false
                }, {
                    "targets": 2, //金额
                    "mRender": function (data, type, row) {
                        return $.number(data);
                    }
                }, {
                    "targets": 3, //资金类型
                    "mRender": function (data, type, row) {
                        return sysFundType[data];
                    }
                }, {
                    "targets": 4, //操作类型
                    "mRender": function (data, type, row) {
                        return sysFundOperation[data];
                    }
                }, {
                    "targets": 5, //资金状态
                    "mRender": function (data, type, row) {
                        return sysFundStatus[data];
                    }
                }, {
                    "targets": 6, //投标时间
                    "searchable": false,
                    "mRender": function (data, type, row) {
                        return $.format.date(new Date(data), "yy/MM/dd HH:mm");
                    }
                }],
            "order": [6, 'desc'],
            "oLanguage": chinese,
            "language": {
                "decimal": ",",
                "thousands": ",",
            },
            "iDisplayLength": 20,
            "aLengthMenu": [
                [5, 10, 20, 50, 100, -1],
                [5, 10, 20, 50, 100, "全部"]
            ],
            "sDom": 't<"dt-panelfooter clearfix"lp>',
            "initComplete": function (settings, json) {
                $("#fundCount").text(json.recordsTotal);
            }
        });

        $('#searchFundRecord').on('click', function () {
            table.ajax.reload();
        });
    };

    /**
     * 初始化借款列表
     */
    var initLoanTable = function () {
        var table = $('#loanTable').DataTable({
//    "processing": true,
//    "serverSide": true,
            "ajax": "loan/getDataByUser/" + user_id,
            "columns": [
                {"data": "title"},
                {"data": "amount"},
                {"data": "rate"},
                {"data": "duration"},
                {"data": "repayMethod"},
                {"data": "status"},
                {"data": "submitTime"}
            ],
            "aoColumnDefs": [{
                    "targets": 0, //标题 
                    "mRender": function (data, type, row) {
                        return data === ''
                            ? '未填写'
                            : '<a href="loan/detail/' + row.id + '">' + data + '</a>';
                    }
                }, {
                    "targets": 1, //金额
                    "mRender": function (data, type, row) {
                        return $.number(data);
                    }
                }, {
                    "targets": 2, //年利率
                    "mRender": function (data, type, row) {
                        return $.number(parseFloat(data / 100), 1) + '%';
                    }
                }, {
                    "targets": 3, //借款周期
                    "mRender": function (data, type, row) {
                        return sys.printDuration(data);
                    }
                }, {
                    "targets": 4, //还款方式
                    "mRender": function (data, type, row) {
                        return sys.getRepayMethod(data);
                    }
                }, {
                    "targets": 5, //状态
                    "searchable": false,
                    "mRender": function (data, type, row) {
                        return sys.getLoanStatus(data);
                    }
                }, {
                    "targets": 6, //申请时间
                    "searchable": false,
                    "mRender": function (data, type, row) {
                        return data !== null
                            ? $.format.date(new Date(data), "yy/MM/dd HH:mm")
                            : '';
                    }
                }],
            "order": [6, "desc"],
            "oLanguage": chinese,
            "language": {
                "decimal": ",",
                "thousands": ","
            },
            "iDisplayLength": 20,
            "aLengthMenu": [
                [5, 10, 20, 50, -1],
                [5, 10, 20, 50, "全部"]
            ],
            "sDom": 't<"dt-panelfooter clearfix"lp>',
            "initComplete": function (settings, json) {
                $("#loanCount").text(json.recordsTotal);
            }
        });
    };

    /**
     * 初始化投标记录
     */
    var initInvestTable = function () {
        var table = $('#investTable').DataTable({
//    "processing": true,
//    "serverSide": true,
            "ajax": "user/getInvestData/" + user_id,
            "columns": [
                {"data": "loanTitle"},
                {"data": "amount"},
                {"data": "status"},
                {"data": "investTime"}
            ],
            "aoColumnDefs": [{
                    "targets": 0, //标的名称 
                    "mRender": function (data, type, row) {
                        return '<a href="loan/detail/' + row.loanId + '" target="_blank">' + data + '</a>';
                    }
                }, {
                    "targets": 1, //金额
                    "mRender": function (data, type, row) {
                        return $.number(data);
                    }
                }, {
                    "targets": 3, //投标时间
                    "searchable": false,
                    "mRender": function (data, type, row) {
                        return $.format.date(new Date(data), "yyyy/MM/dd HH:mm");
                    }
                }, {
                    "targets": 2, //状态
                    "searchable": false,
                    "mRender": function (data, type, row) {
                        return sysInvestStatus[data];
                    }
                }],
            "order": [3, "desc"],
            "oLanguage": chinese,
            "language": {
                "decimal": ",",
                "thousands": ","
            },
            "iDisplayLength": 20,
            "aLengthMenu": [
                [5, 10, 20, 50, -1],
                [5, 10, 20, 50, "全部"]
            ],
            "sDom": 't<"dt-panelfooter clearfix"lp>',
            "initComplete": function (settings, json) {
                $("#investCount").text(json.recordsTotal);
            }
        });
    };

    /**
     * 初始化事件
     */
    var initEvents = function () {
        // 账号激活/冻结
        $("#changeStatus").on("click", function () {
            if (confirm('确定要更新用户状态？')) {
                $.get("user/changeStatus/" + user_id, function (res) {
                    if (res.success) {
                        alert(res.message);
                        location.reload();
                    } else {
                        alert("用户状态更新失败");
                    }
                });
            }
        });
    };

    var initPage = function () {
        initEvents();
        initUserFund();
        initFundRecordTable();
        initLoanTable();
        initInvestTable();
    };

    // 初始化页面
    initPage();
});